package com.sk.places.places2.filter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sk.places.places2.business.service.UserService;
import com.sk.places.places2.business.service.UserServiceImpl;
import com.sk.places.places2.fb.service.AppConstants;
import com.sk.places.places2.fb.service.FBService;
import com.sk.places.places2.fb.service.FBServiceImpl;
import com.visural.common.StringUtil;

/**
 * Servlet Filter implementation class FBOAuthFilter
 */
public class FBOAuthFilter implements Filter {

	private Logger logger = Logger.getLogger(getClass().getName()) ; 
	
	//TODO - Use IOC (e.g. spring) to inject these implementations
	private UserService userService  = new UserServiceImpl(); 
	private FBService fbService = new FBServiceImpl() ; 
    /**
     * Default constructor. 
     */
    public FBOAuthFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		logger.info(" Entered " + getClass().getName()) ;
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        String code = req.getParameter("code");
        logger.info(" The code is " + code) ;
        if (StringUtil.isNotBlankStr(code)) {
            String authURL = fbService.getAuthURL(code);
            URL url = new URL(authURL);
            try {
                String result = readURL(url);
                String accessToken = null;
                Integer expires = null;
                String[] pairs = result.split("&");
                for (String pair : pairs) {
                    String[] kv = pair.split("=");
                    if (kv.length != 2) {
                        throw new RuntimeException("Unexpected auth response");
                    } else {
                        if (kv[0].equals("access_token")) {
                            accessToken = kv[1];
                        }
                        if (kv[0].equals("expires")) {
                            expires = Integer.valueOf(kv[1]);
                        }
                    }
                }
                if (accessToken != null && expires != null) {
                	userService.getFacebookUser(accessToken, expires);
                    
                } else {
                    throw new RuntimeException("Access token and expires not found");
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
	}
	

    private String readURL(URL url) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = url.openStream();
        int r;
        while ((r = is.read()) != -1) {
            baos.write(r);
        }
        return new String(baos.toByteArray());
    }

    
	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
